﻿using UnityEngine;
using Size = System.Drawing.Size;
using Point = System.Drawing.Point;
using System.Collections.Generic;

public static class GameObjectEx
{
    public static float Size => GameSize.Height * 1f / 100 / 2;
    static float WSize => GameSize.Width * 1f / 100 / 2;
    public static Size GameSize { get; set; } = new Size(1920, 1080);
    public static int sort = -999;
    public static void ChangeSize(Size size)
    {
        GameSize = size;
        Screen.SetResolution(size.Width, size.Height, Screen.fullScreen);
        Camera.main.orthographicSize = Size;
        for (var i = 0; i < _controls.Count; i++)
        {
            ChangePosition(_controls[i], _locations[_controls[i]]);
        }
    }
    public static void Location(this GameObject control,int x, int y)
	{
        Location(control, new Point(x, y));
    }
    static List<GameObject> _controls = new List<GameObject>();
    static Dictionary<GameObject,Point> _locations = new Dictionary<GameObject, Point>();

    public static void Location(this GameObject control, Point locaton)
    {
        control.ChangePosition(locaton);
        _controls.Add(control);
        _locations.Add(control,locaton);
    }
    public static void ChangePosition(this GameObject control, int x,int y)
    {
        control.ChangePosition(new Point(x, y));
    }
    public static void ChangePosition(this GameObject control,Point locaton)
    {
        var offset = Vector2.zero;

        var rect = control.GetComponent<RectTransform>();
        if (rect.GetComponent<SpriteRenderer>() != null)//image
            rect.GetComponent<SpriteRenderer>().sortingOrder = sort;
        else//textfield
        {
            if (locaton != Point.Empty)
            {
                locaton.X += (int)rect.sizeDelta.x;
                locaton.Y += (int)rect.sizeDelta.y;
            }
        }
            
        sort++;
       
        if (locaton != Point.Empty)
        {
            var size = new Vector2(WSize * 2, Size * 2);
            var scale = new Vector2(locaton.X * 1f / GameSize.Width, locaton.Y * 1f / GameSize.Height);
            offset = size * scale;
        }

        rect.anchorMin = new Vector2(0.5f, 0.5f);
        rect.anchorMax = new Vector2(0.5f, 0.5f);
        rect.position = new Vector2(-WSize + offset.x, Size - offset.y);
        rect.pivot = new Vector2(0.5f, 0.5f);
    }
}

